<template>
    <div class="branding-manage">

        <UserFixedHead :title="form.id ? 'Edit neck label' : 'Create neck label'" />

        <h2 v-text="form.id ? 'Edit neck label' : 'Create neck label'"></h2>

        <div class="branding-manage-warp">
            <div class="branding-manage-nav">
                <span @click="$emit('close')">Branding</span>
                <i class="iconfont icon-you"></i>
                <strong v-text="form.id ? 'Edit neck label' : 'Create neck label'"></strong>
            </div>

            <h3>Neck label name</h3>
            <input type="text" v-model="form.title" maxlength="64" placeholder="Label name" />
            <ul>
                <li>
                    <h4>Neck label for dark-colored clothes</h4>
                    <figure :empty="!form.dark">
                        <!-- <img v-if="form.dark" crossOrigin="anonymous" v-lazy="$getLitimgUrl(form.dark.output_img,'medium')" /> -->
                        <CommonDesignSurfacePreivew v-if="form.dark" :pieces="[form.dark]"
                                                    :surface="getPieceSurface(form.dark)" />
                        <img v-else
                             src="https://img.podpartner.com/static/images-20230202/branding-placeholder-dark.png" />
                    </figure>
                    <fieldset>
                        <button type="primary" @click="openUploader('dark')">Upload</button>
                        <button v-if="form.dark" @click="setEditor('dark')">Edit</button>
                    </fieldset>
                </li>
                <li>
                    <h4>Neck label for light-colored clothes</h4>
                    <figure :empty="!form.light">
                        <!-- <img v-if="form.light" crossOrigin="anonymous" v-lazy="$getLitimgUrl(form.light.output_img,'medium')" /> -->
                        <CommonDesignSurfacePreivew v-if="form.light" :pieces="[form.light]"
                                                    :surface="getPieceSurface(form.light)" />
                        <img v-else
                             src="https://img.podpartner.com/static/images-20230202/branding-placeholder-light.png" />
                    </figure>
                    <fieldset>
                        <button type="primary" @click="openUploader('light')">Upload</button>
                        <button v-if="form.light" @click="setEditor('light')">Edit</button>
                    </fieldset>
                </li>
            </ul>

            <p>
                <i class="iconfont icon-xiangqing1"></i> File requirements:
                1.JPG and PNG file types supported； 2.Maximum file size 50MB.
            </p>

            <div class="branding-manage-example">
                <h4>Custom neck label example</h4>
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/branding-example.png" alt="" />
                </figure>
            </div>

            <div class="branding-manage-save" :class="{ active: change }">
                <cite>
                    <button @click="$emit('close')">Cancel</button>
                    <button type="primary" @click="updateBrand()">Save</button>
                </cite>
            </div>
        </div>

        <!-- 图片上传 -->
        <UserUploader ref="uploader" />

        <!-- 编辑器 -->
        <UxDialog :visible="!!editor" class="design-editor-dialog" title="Custom neck label" :can-close="false">
            <CommonDesignEditor v-if="editor" :design="editor.design" @close="editor.close($event)"
                                @update="editor.save($event)">
                <template slot="tooler" slot-scope="scope">
                    <h2 v-if="editor.theme == 'dark'">Neck label for dark-colored clothes</h2>
                    <h2 v-if="editor.theme == 'light'">Neck label for light-colored clothes</h2>
                    <BrandingNecklabelEditorTooler :activePiece="scope.activePiece" :activeLayer="scope.activeLayer" />
                </template>
            </CommonDesignEditor>
        </UxDialog>

        <UxDialog :visible="!!saving" class="saving-dialog" :status="saving" :can-close="false">

            <div class="saving-loading" v-if="saving == 'loading'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/branding-saving.png" alt="" />
                </figure>
                <img src="@/assets/images/pay-loading.gif" />
                <strong>Your design is being saved</strong>
            </div>

            <div class="saving-success" v-if="saving == 'success'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/branding-success.png" alt="" />
                </figure>
                <p><span>Successfully saved</span></p>
                <fieldset>
                    <button type="primary" @click="onSuccess()">OK</button>
                </fieldset>
            </div>

            <div class="saving-failure" v-if="saving == 'failure'">
                <figure>
                    <img src="https://img.podpartner.com/static/images-20230202/branding-failure.png" alt="" />
                </figure>
                <p>
                    <strong>Failed to save</strong><span>Please check your network</span>
                </p>
                <fieldset>
                    <button v-if="editor" @click="editor.save(editor.pieces)">Save again</button>
                    <button v-else @click="updateBrand()">Save again</button>
                </fieldset>
            </div>
        </UxDialog>
    </div>
</template>
<script>
import DesignResource from "@/utils/DesignResource.js";
import DesignUtils from "@/utils/DesignUtils.js";
import Md5 from "js-md5";
import { mapGetters } from "vuex";
export default {
    name: "BrandingNecklabelManage",
    props: {
        detail: { type: Object, default: false },
    },
    data () {
        return {
            editor: null,
            saving: '',
            cache: null,
            form: {
                id: '',
                title: '',
                dark: null,
                light: null,
            }
        };
    },
    computed: {
        ...mapGetters("user", {
            userInfo: "getUserInfo",
        }),
        change () {
            if (!this.cache) {
                return false;
            } else if (this.cache.title != this.form.title) {
                return true;
            } else if (this.cache.dark != JSON.stringify(this.form.dark)) {
                return true;
            } else if (this.cache.light != JSON.stringify(this.form.light)) {
                return true;
            } else {
                return false;
            }
        },
    },
    methods: {
        // 保存或更新
        async updateBrand () {
            if (!this.detail) {
                // 没有详情不保存
            } else if (!this.form.title) {
                this.$uxMessage.error("Please name your neck label.");
            } else {

                const request = {
                    id: this.form.id || "",
                    title: this.form.title,
                    dark_design: this.form.dark ? { ...this.form.dark } : "",
                    light_design: this.form.light ? { ...this.form.light } : "",
                };

                const drawer = {
                    spu: 'necklabel',
                    pieces: [],
                    models: [],
                }

                request.dark_design && drawer.pieces.push({ id: 'dark', ...request.dark_design })
                request.light_design && drawer.pieces.push({ id: 'light', ...request.light_design })

                this.saving = 'loading';
                this.$http("Drawer.batchDraw", drawer).then((response) => {
                    if (response.code === 0) {

                        const data = response.data || [];
                        const httpKey = request.id ? "BrandLabel.update/" + request.id : "BrandLabel.insert";

                        data.map(res => {
                            if (res.id == 'dark') {
                                request.dark_design.output_img = res.output.replace(/-litimg(\.(jpe?g|png))/gi, "$1")
                            } else if (res.id == 'light') {
                                request.light_design.output_img = res.output.replace(/-litimg(\.(jpe?g|png))/gi, "$1")
                            }
                        })

                        request.dark_design.layers = JSON.stringify(request.dark_design.layers)
                        request.light_design.layers = JSON.stringify(request.light_design.layers)



                        return this.$http(httpKey, request);
                    } else {
                        return Promise.reject(response);
                    }
                }).then(response => {
                    if (response.code === 0) {
                        this.getCache();
                        this.saving = 'success';
                    } else {
                        this.saving = 'failure';
                    }

                }).catch(error => {
                    this.saving = 'failure';
                })


            }
        },

        // 打开上传器
        openUploader (type) {

            const email = (this.userInfo || {}).email;
            const folder = email ? Md5(email) : 'necklabel';
            const path = 'data/pod/file/' + folder;

            this.$refs.uploader && this.$refs.uploader.startUpload({ path: path }, result => {

                const option = {
                    image: result.image,
                    imageW: result.image.width,
                    imageH: result.image.height,
                    name: result.name,
                    url: result.url,
                }

                DesignResource.setImageCache(result.url, result.image)
                this.setEditor(type, option);
                this.$refs.uploader.close();
            });
        },

        setEditor (type, event) {
            const getPiece = (design, event) => {
                if (!design && !event) {
                    // 啥都没有，啥都不干
                } else if (!design && event) {
                    // 创建
                    const mask = type == "dark" ? "brand/dark.svg" : "brand/light.svg";
                    const color = type == "dark" ? "#fff" : "#000";

                    const piece = {
                        surface_name: "Neck Label Inner", // 画板名称
                        canvas_name: "Neck Label Inner", // 画板名称
                        mask_image: mask, // 遮罩图片，宽度高度与容器一至
                        outer_width: 2048, // 容器宽度
                        outer_height: 2048, // 容器高度
                        real_width: 900, // 容器宽度
                        real_height: 900, // 容器高度
                        canvas_zoom: 1,
                        canvas_left: 535, // 画板相对容器的左边的位置
                        canvas_top: 735, // 画板相对容器的左边的位置
                        canvas_width: 981, // 画板的宽度
                        canvas_height: 981, // 画板的宽度
                        canvas_rotate: 0, // 画板旋转角度
                        price: 0, // 设计面价格
                        layers: [],
                    };

                    let image = DesignUtils.resetImage(
                        {
                            id: 0,
                            type: "image", // 类型[image|text]
                            url: event.url,
                            name: event.name,
                            imageW: event.imageW, // 图片宽度
                            imageH: event.imageH, // 图片高度
                        },
                        piece
                    );

                    let size = DesignUtils.resetText(
                        {
                            id: 1,
                            font_size: 200,
                            type: "text", // 类型[image|text]
                            text: "2XL", // 文字内容
                        },
                        piece
                    );

                    size.font_color = color;

                    // 添加背景图
                    piece.layers.push(image);
                    piece.layers.push(size);

                    return piece;
                } else if (design && !event) {
                    // 再次编辑
                    return JSON.parse(JSON.stringify(design));
                } else if (design && event) {
                    // 替换图片编辑

                    let piece = JSON.parse(JSON.stringify(design));
                    let image = piece.layers[0];

                    image.url = event.url;
                    image.name = event.name;
                    image.imageW = event.imageW; // 图片宽度
                    image.imageH = event.imageH; // 图片高度

                    DesignUtils.resetImage(image, piece);
                    return piece;
                }
            };

            this.editor = {
                theme: type,
                design: [getPiece(this.form[type], event)],
                close: (change) => {
                    if (change) {
                        this.$parent.dialog_leave = (leave) => {
                            if (leave) {
                                this.editor = null
                                this.$parent.dialog_leave = null;
                            } else {
                                this.$parent.dialog_leave = null;
                            }
                        };

                    } else {
                        this.editor = null
                    }
                },
                save: (design) => {

                    this.form[type] = design[0];
                    this.editor = null;
                },
            }
        },

        getPieceSurface (piece) {

            const maxSize = Math.max(piece.canvas_width, piece.canvas_height) || 1;
            const width = piece.outer_width * piece.canvas_width / maxSize;
            const height = piece.outer_height * piece.canvas_height / maxSize;
            const left = (piece.outer_width - width) / 2;
            const top = (piece.outer_height - height) / 2;

            return {
                "surface_name": piece.canvas_name,
                "name": piece.canvas_name,
                "mask_image": null,
                "outer_width": piece.outer_width,
                "outer_height": piece.outer_height,
                "mask_color": "",
                "mask_opacity": 0,
                "mapping_top": true,
                "mapping": [{
                    "canvas_name": piece.canvas_name,
                    "variant_deform": 0,
                    "variant_factor": 0,
                    "height": height,
                    "width": width,
                    "rotate": 0,
                    "clip": "",
                    "x": left,
                    "y": top
                }]
            }

        },


        // 成功
        onSuccess () {
            if (this.editor) {
                this.editor = null;
                this.saving = '';
            } else {
                this.saving = '';
                this.$nextTick(e => {
                    this.$emit("update");
                    this.$emit("close");
                })
            }
        },


        // 预加载图片
        preLoadImage () {
            const option = { type: "simple", form: "materials" };

            const dark = (this.form.dark || {}).layers || [];
            const light = (this.form.light || {}).layers || [];

            // 加载背景
            DesignResource.loadImage("brand/dark.svg", option);
            DesignResource.loadImage("brand/light.svg", option);
            // 加载字体
            DesignResource.loadAllFont();

            // 加载图层
            dark.concat(light).map((item) => {
                item.type == "image" &&
                    item.url &&
                    DesignResource.loadImage(item.url, option);
            });
        },

        getDetail () {

            this.form.id = this.detail.id;
            this.form.title = this.detail.title;
            this.form.dark = this.detail.dark;
            this.form.light = this.detail.light;

            if (this.form.dark && Object.prototype.toString.call(this.form.dark.layers) == "[object String]") {
                this.form.dark.layers = JSON.stringify(this.form.dark.layers);
            }

            if (this.form.light && Object.prototype.toString.call(this.form.light.layers) == "[object String]") {
                this.form.light.layers = JSON.stringify(this.form.light.layers);
            }

        },
        getCache () {
            this.cache = {
                id: this.form.id,
                title: this.form.title,
                dark: JSON.stringify(this.form.dark),
                light: JSON.stringify(this.form.light),
            }
        }

    },
    created () {
        this.getDetail();
        this.getCache();
        this.preLoadImage();
    },
};
</script>
<style lang="scss" scoped>
.branding-manage {
    flex: 1;
    position: relative;
    display: flex;
    flex-direction: column;

    &>h2 {
        line-height: 72px;
        background: #fff;
        border-radius: 8px;
        font-size: 32px;
        color: #000000;
        text-align: center;
    }

    .branding-manage-nav {
        margin-top: 28px;
        height: 16px;
        font-size: 14px;
        color: #555555;
        line-height: 16px;

        display: flex;

        span {
            cursor: pointer;

            &:hover {
                color: #ea4c89;
            }
        }

        i {
            display: inline-block;
            margin: 0 8px;
            width: 12px;
            height: 16px;
            font-size: 12px;
        }

        strong {
            font-weight: normal;
            color: #000;
        }
    }

    .branding-manage-warp {
        background: #fff;
        border-radius: 8px;
        margin-top: 20px;
        padding: 0 162px 80px;

        h3 {
            margin-top: 32px;
            font-size: 16px;
            color: #000000;
            line-height: 18px;
        }

        input {
            margin-top: 12px;
            width: 480px;
            height: 40px;
        }

        ul {
            background: #f6f6f6;
            border-radius: 6px;
            border: 1px solid #f0f0f0;
            display: flex;
            padding: 40px 0;
            margin-top: 24px;
            min-width: 766px;

            li {
                width: 280px;
                margin: 0 50px;
                text-align: center;

                &:first-child figure {
                    background-color: #000;

                    img {
                        border-color: #686666;
                    }
                }
            }

            h4 {
                width: 100%;
                font-size: 14px;
                color: #000000;
                line-height: 18px;
            }

            figure {
                margin-top: 12px;
                padding: 25px;
                position: relative;
                background-color: #fff;
                border-radius: 4px;

                .surface-preview {
                    border: 1px dashed #bdbdbd;
                }

                &>img {
                    width: 228px;
                    height: 228px;
                    border: 1px dashed #bdbdbd;
                }
            }

            fieldset {
                display: flex;
                justify-content: center;

                button {
                    margin-top: 28px;
                    flex: 1;
                    max-width: 128px;
                    height: 38px;
                    font-size: 14px;
                    background-color: #fff;

                    &[type='primary'] {
                        background: #ea4c89;

                        &:hover {
                            background: #c94175;
                            color: #ffffff;
                        }
                    }

                    &+button {
                        margin-left: 16px;
                    }
                }
            }
        }

        p {
            margin-top: 14px;
            font-size: 12px;
            color: #000000;
            line-height: 14px;

            i {
                font-size: 14px;
                vertical-align: top;
                margin-right: 4px;
                color: #acacac;
            }
        }
    }

    .branding-manage-example {
        margin-top: 54px;

        h4 {
            font-size: 16px;
            color: #000000;
            line-height: 18px;
        }

        figure {
            margin-top: 14px;
            padding-bottom: 36.34%;
            background: #f6f6f6;
            border-radius: 6px;
            position: relative;

            img {
                position: absolute;
                left: 0;
                top: 0;
                width: 100%;
                height: 100%;
            }
        }
    }

    .branding-manage-save {
        position: fixed;
        left: 228px;
        right: 0;
        padding-left: 32px;
        padding-right: 32px;
        bottom: 0;
        height: 90px;
        max-width: initial !important;
        width: initial !important;
        text-align: center;
        opacity: 0;
        z-index: 1;
        transition: opacity 0.5s;
        pointer-events: none;

        cite {
            border-top: 1px solid #dcdcdc;
            display: block;
            margin: 0 auto;
            max-width: 1080px;
            padding: 20px 0 40px;
            background: #fff;
        }

        button {
            width: 160px;
            height: 40px;
            margin: 0 12px;

            &[type='primary'] {
                width: 360px;
            }
        }

        &.active {
            opacity: 1;
            pointer-events: all;
        }

        &.loading::after {
            content: '';
            position: absolute;
            left: 0;
            top: 0;
            width: 100%;
            height: 100%;
            background-color: rgba(255, 255, 255, 0.9);
        }

        button {
            margin: 0 10px;
        }
    }
}

.design-editor-dialog {
    padding: 0 !important;
    background: none !important;

    &::v-deep>.dialog-content {
        width: 100vw;
        height: 100vh;

        &>h2 {
            height: 78px;
            line-height: 78px;
            font-size: 24px;
            font-weight: bold;
            color: #000000;
        }

        &>h6 {
            display: none;
        }

        .dialog-body {
            display: flex;
            width: 100vw;
            height: calc(100vh - 40px);

            .tooler-nodata figure {
                width: 140px;

                &::before {
                    background-image: url(https://img.podpartner.com/static/images-20230202/brand/package-design-nodata.png);
                    background-size: 100% 100%;
                }

                svg {
                    display: none;
                }
            }

            .editor-operate-drager button:nth-child(4) {
                display: none;
            }

            .layout-surface {
                display: none;
            }

            .tooler-slot>h2 {
                font-size: 22px;
                color: #000000;
                line-height: 24px;
                padding: 32px 0;
                text-align: center;
            }
        }
    }
}

.saving-dialog {
    &[status='loading']::v-deep .dialog-content {
        border-radius: 38px;

        &>h6 {
            display: none;
        }
    }

    &[status='success']::v-deep .dialog-content>h6 {
        display: none;
    }

    .saving-loading {
        display: flex;
        flex-direction: column;
        align-items: center;
        justify-content: center;
        box-sizing: border-box;
        width: 400px;
        height: 280px;
        background: #fafafa;
        border-radius: 38px;

        figure {
            width: 66px;
            height: 66px;
            margin-bottom: 24px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        &>img {
            height: 8px;
        }

        strong {
            margin-top: 24px;
            font-size: 18px;
            color: #000000;
            line-height: 18px;
            text-align: center;
        }
    }

    .saving-success,
    .saving-failure {
        width: 320px;
        height: 414px;
        box-sizing: border-box;
        display: flex;
        flex-direction: column;
        align-items: center;
        padding: 40px 20px 26px;

        figure {
            margin-top: 50px;
            width: 80px;
            height: 80px;

            img {
                width: 100%;
                height: 100%;
            }
        }

        p {
            height: 120px;
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            font-size: 16px;
            color: #000000;
            line-height: 20px;
            text-align: center;

            strong {
                color: #000000;
                margin-bottom: 8px;
            }
        }

        fieldset {
            display: flex;
            flex-direction: column;
            width: 100%;
            margin-top: 60px;

            button+button {
                margin-top: 8px;
            }
        }
    }
}
</style>
